package cn.com.transfer.services;

import cn.com.transfer.params.IcbcParams;
import cn.com.transfer.utils.Constants;
import cn.com.transfer.utils.IcbcNative;
import cn.com.transfer.utils.TransLog;
import com.sun.org.apache.xpath.internal.operations.Bool;
import flexjson.JSONSerializer;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static cn.com.transfer.utils.IcbcInfo.schoolId;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 冲正(已对账记录不能冲正)
 */
public class ReverseTrans extends MsgHandlerService {
    private Logger logger = LoggerFactory.getLogger(ReverseTrans.class);

    @Override
    public String handler(Map params) {
        Map rtn = new HashMap();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            Cnd cnd = Cnd.where("transNo", "=", params.get("transNo")).and("CONVERT(varchar(100), serviceAt, 112)", "=", format.format(new Date()));
            Record log = dao.fetch("icbcQCLog", cnd);
            Calendar cal = Calendar.getInstance();

            IcbcParams req = new IcbcParams(2);
            req.schoolCode = schoolId;
            req.transCode = Constants.ICBC_TRANS_SIGN_REVER;
            req.transType = Constants.ICBC_TRANS_TYPE_RECHARGE;
            req.transMark = "1";
            req.transTime = String.format("%02d:%02d:%02d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
            req.transDate = String.format("%04d-%02d-%02d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH));
            cal.add(Calendar.DAY_OF_MONTH, 1);
            req.accDate = String.format("%04d-%02d-%02d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH));
            req.terminalNo = log.getString("terminalNo");
            req.transNo = getTransNo();
            req.oldTransNo = log.getString("transNo");
            req.yktNo = log.getString("accountNo");
            req.bankCardNo = IcbcNative.encrypt(String.format("%-24s", log.getString("bankNo")), 1);
            req.money = IcbcNative.encrypt(String.format("%-16s", log.getString("amount")), 1);
            req.mac = req.genMac(1);

            IcbcParams resp = sendMessage(req);

            Chain ch;
            if (resp == null || !resp.rtnCode.equals("00000")) {
                rtn.put("success", false);
                ch = Chain.make("reverse", 2);
                logger.error(resp == null ? "连接服务器失败" : (resp.rtnMsg == null ? (String) Constants.msgMap.get(resp.rtnCode) : resp.rtnMsg));
            } else {
                rtn.put("success", true);
                ch = Chain.make("reverse", 1);
            }
            dao.update("icbcQCLog", ch, cnd);

            if (params.get("writeLog") != null && (Boolean) params.get("writeLog")) {
                Record customer = dao.fetch("tb_customer", Cnd.where("accountNo", "=", log.get("accountNo")));
                BigDecimal accLeftMoney = BigDecimal.valueOf(Double.valueOf(log.getString("amount")) / -100);
                TransLog.addRechargeLog(customer, accLeftMoney, dao);
                dao.update("tb_customer", Chain.make("leftMoney", ((BigDecimal) customer.get("LeftMoney")).add(accLeftMoney)),
                        Cnd.where("accountNo", "=", customer.get("accountNo")));
            }

        } catch (Exception e) {
            logger.error("error in ReverseTrans", e);
            rtn.put("success", false);
            rtn.put("msg", e.getMessage() != null ? e.getMessage() : e.toString());
        }

        return new JSONSerializer().serialize(rtn);
    }
}
